import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/',
    redirect: '/config'  // 重定向到配置页面
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/config',
    name: 'config',
    component: () => import('../views/ConfigView.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: 'preview'
      },
      {
        path: 'preview',
        name: 'preview',
        component: () => import('../components/live/preview.vue')
      },
      {
        path: 'camera/video',
        name: 'video',
        component: () => import('../components/camera/VideoConfig.vue')
      },
      {
        path: 'camera/osd',
        name: 'osd',
        component: () => import('../components/camera/OSDConfig.vue')
      },
      {
        path: 'camera/audio_param',
        name: 'audio_param',
        component: () => import('../components/camera/AudioConfig.vue')
      },
      {
        path: 'camera/audio',
        name: 'audio',
        component: () => import('../components/camera/AudioManagement.vue')
      },
      {
        path: 'network/basic',
        name: 'basic',
        component: () => import('../components/network/BasicConfig.vue')
      },
      {
        path: 'network/gb28181',
        name: 'gb28181',
        component: () => import('../components/network/GB28181Config.vue')
      },
      {
        path: 'network/rtsp',
        name: 'rtsp',
        component: () => import('../components/network/RTSPConfig.vue')
      },
      {
        path: 'network/rtmp',
        name: 'rtmp',
        component: () => import('../components/network/RTMPConfig.vue')
      },
      {
        path: 'operations/upgrade',
        name: 'upgrade',
        component: () => import('../components/system/UpgradeConfig.vue')
      },
      {
        path: 'intelligence/model',
        name: 'model',
        component: () => import('../components/intelligence/ModelManage.vue')
      },
      {
        path: 'intelligence/algo',
        name: 'algo',
        component: () => import('../components/intelligence/AlgoManage.vue')
      },
      {
        path: 'intelligence/cloud-model',
        name: 'cloud-model',
        component: () => import('../components/intelligence/CloudModelConfig.vue')
      },
      {
        path: 'system/user',
        name: 'user',
        component: () => import('../components/system/UserManage.vue')
      },
      {
        path: 'system/datetime',
        name: 'datetime',
        component: () => import('../components/system/DateTimeConfig.vue')
      },
      {
        path: 'system/factory_reset',
        name: 'factory_reset',
        component: () => import('../components/system/FactoryResetConfig.vue')
      },
      {
        path: 'record/playback',
        name: 'playback',
        component: () => import('../components/record/VideoPlayback.vue')
      }
    ]
  },
  // 重定向所有/preview和/live到/config/preview
  {
    path: '/preview',
    redirect: '/config/preview'
  },
  {
    path: '/live',
    redirect: '/config/preview'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth !== false);

  // 获取认证状态
  const isAuthenticated = localStorage.getItem('access_token');
  const tokenExpires = localStorage.getItem('token_expires');
  const isTokenExpired = tokenExpires && parseInt(tokenExpires) < Date.now();

  // 如果token过期，清除认证信息
  if (isTokenExpired) {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('token_expires');
    localStorage.removeItem('user_info');
  }

  if (requiresAuth && (!isAuthenticated || isTokenExpired)) {
    // 需要认证但未登录或token过期，保存原始请求路径并重定向到登录页面
    localStorage.setItem('redirect_after_login', to.fullPath);
    next('/login');
  } else if (to.path === '/login' && isAuthenticated && !isTokenExpired) {
    // 已登录且token未过期的用户访问登录页面
    // 检查是否有保存的重定向路径
    const redirectPath = localStorage.getItem('redirect_after_login');
    if (redirectPath) {
      localStorage.removeItem('redirect_after_login');
      next(redirectPath);
    } else {
      next('/config');
    }
  } else {
    // 其他情况正常导航
    next();
  }
})

export default router
